package com.jsgt.greekfire.common.widget

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText

/**
 * 输入只允许输入数字时
 * 设置最大小数位数及输入非法内容的处理
 */
fun EditText.maxDecimalPlace(size: Int) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            if (!s.isNullOrEmpty()) {
                try {
                    s.toString().toDouble()
                    val temp = s.toString()
                    val posDot = temp.indexOf(".")
                    if (posDot <= 0) return
                    if (temp.length - posDot - 1 > size) {
                        s.delete(posDot + size + 1, posDot + size + 2)
                    }
                } catch (error: java.lang.Exception) {
                    s.delete(s.length - 1, s.length)
                }
            }
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        }
    })
}